//
// Created by denglibin on 2021/9/6.
//
#include "01_listen_port.h"
#include <event2/listener.h>
#include "init.h"
#define SPORT 5001
/**
 * 接收到连接的回调函数
 * @param evconnlistener
 * @param fd
 * @param addr
 * @param socklen
 * @param arg
 */
static void listen_cb(struct evconnlistener * evconnlistener, evutil_socket_t fd, struct sockaddr * addr, int socklen, void * arg);

int demo_1()
{
    init();
    printf("test server!\n");
    //创建libevent 上下文
    struct event_base* base = event_base_new();
    if(!base){
        clean();
        printf("event_base_new fail!");
        return 1;
    }
    struct sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(SPORT);
    //监听端口
    struct evconnlistener * listener = evconnlistener_new_bind(base,
                                                               listen_cb,                                       //回调函数
                                                               base,                                            //自定义数据
                                                               LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, //地址重用，listen关闭socket
                                                               10,                                      //连接缓冲队列大小
                                                               (struct sockaddr*)&sin,                          //端口
                                                               sizeof(sin));

    //事件分发处理
    event_base_dispatch(base);

    //释放
    evconnlistener_free(listener);
    //释放
    event_base_free(base);
    clean();
    return (0);
}

void listen_cb(struct evconnlistener * evconnlistener, evutil_socket_t fd, struct sockaddr * addr, int socklen, void * arg){
    printf("listen_cb\n");
}
